package com.lzs.kunei.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzs.entity.*;
import com.lzs.kucun.service.StockService;
import com.lzs.kunei.service.MoveService;
import com.lzs.kunei.service.PutonService;
import com.lzs.util.JwtUtils;
import com.lzs.util.R;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wpy
 * @since 2020-11-24
 */

@RestController
@RequestMapping("/kunei/move")
@ApiModel(value = "移库的操作")
public class MoveController {
    @Autowired
    private MoveService moveService;
    @Autowired
    private PutonService putonService;
    @Autowired
    private StockService stockService;
    @ApiOperation(value = "查询移库管理信息")
    @PostMapping("/selectMovePage/{current}/{size}")
    public R selectPutonPage(@PathVariable Integer current,  @PathVariable Integer size, @RequestBody Move move,HttpServletRequest request){
        Page<Move> movePage=null;
        try {
            String warehouseId = request.getHeader("warehouseId");
           // System.out.println(warehouseId);
            String[] warehouseid = warehouseId.split(",");
            movePage = moveService.selectMovePage(current, size, move,warehouseid);
            return R.ok().message("查询成功").data("movePage",movePage);
        }catch (RuntimeException e){
            e.printStackTrace();
            return R.error().message("查询出错").data("movePage",movePage);
        }
    }
    @ApiOperation(value = "审核")
    @PostMapping("/updateAudit")
    public R updateAudit(@RequestBody List<Puton> list, HttpServletRequest request) {
        try {
            String token=request.getHeader("token");
            Long userid= JwtUtils.getMemberIdByJwtToken(token);
            User user=stockService.selectUser(userid);
            String name = user.getName();
            int j=1;
            for (int i = 0; i < list.size(); i++) {
                Puton puton = list.get(i);
                if (!puton.getState().equals("1")){
                    return R.error().message("存在通过审核的订单,或者不可用的订单,请重新选择");
                }
            }
            for (int i = 0; i < list.size(); i++) {
                Puton move = list.get(i);
                QueryWrapper<Move> putonQueryWrapper = new QueryWrapper<>();
                putonQueryWrapper.eq("id", move.getId());
                Move move1 = new Move();
                move1.setState("2");
                move1.setAuditid(userid);
                move1.setAuditor(name);
                move1.setAudittime(new Date());
                String commoditybar = move.getCommoditybar();
                Integer qty = move.getQty();
                String locatorcode = move.getLocatorcode();
                String oldlocatorcode = move.getOldlocatorcode();
                Long warehouseid = move.getWarehouseid();
                R r = stockService.updateLqtyQuantity(oldlocatorcode,commoditybar,warehouseid,qty);
                if (!r.getSuccess()){
                    j=0;
                    continue;
                }
                if (r.getSuccess()) {
                    moveService.update(move1, putonQueryWrapper);
                    Stock stock = new Stock();
                    stock.setUqty(move.getQty());
                    stock.setCqty(move.getQty());
                    stock.setLqty(0);
                    BeanUtils.copyProperties(move, stock);
                    if (!stockService.selectIsExit(locatorcode,commoditybar,warehouseid)){
                        Locator locator = stockService.selectLocator(locatorcode);
                        Commodity commodity = stockService.selectCommodity(commoditybar);
                        stock.setLocatorid(locator.getId());
                        stock.setLocatorname(locator.getName());
                        stock.setCommodityid(commodity.getId());
                        stock.setCommodityname(commodity.getName());
                        stock.setCreateid(userid);
                        stock.setCreator(name);
                        stockService.save(stock);
                    }else {
                        stockService.updateAllQuantity(locatorcode,commoditybar,warehouseid,qty);
                    };//修改库存管理的可用和总数量
                }
            }
            if (j==1){
                return R.ok().message("全部已审核");
            }else {
                return R.ok().message("存在未审核通过的订单");
            }

        } catch (RuntimeException e) {
            e.printStackTrace();
            return R.error().message("审核出错");
        }

    }
    @ApiOperation(value = "取消审核")
    @PostMapping("/cancelAudit")
    public R cancelAudit(@RequestBody List<Puton> list,HttpServletRequest request) {
        try {
            String token=request.getHeader("token");
            Long userid= JwtUtils.getMemberIdByJwtToken(token);
            User user=stockService.selectUser(userid);
            String name = user.getName();
            int j=1;
            for (int i = 0; i < list.size(); i++) {
                Puton puton = list.get(i);
                if (!puton.getState().equals("2")){
                    return R.error().message("存在未通过审核的订单,或者不可用的订单,请重新选择");
                }
            }
            for (int i = 0; i < list.size(); i++) {
                Puton move = list.get(i);
                QueryWrapper<Move> putonQueryWrapper = new QueryWrapper<>();
                putonQueryWrapper.eq("id", move.getId());
                Move move1 = new Move();
                move1.setState("3");
                move1.setUpdateid(userid);
                move1.setUpdator(name);
                String commoditybar = move.getCommoditybar();
                Integer qty = move.getQty();
                String locatorcode = move.getLocatorcode();
                String oldlocatorcode = move.getOldlocatorcode();
                Long warehouseid = move.getWarehouseid();
                R r = stockService.reduceQuantity(locatorcode,commoditybar,warehouseid,qty);
                if (!r.getSuccess()){
                    j=0;
                    continue;
                }
                if (r.getSuccess()) {
                    moveService.update(move1, putonQueryWrapper);
                    stockService.updateAllQuantity(oldlocatorcode,commoditybar,warehouseid,qty);
                    };//修改库存管理的可用和总数量
                }
            if (j==1){
                return R.ok().message("全部取消审核");
            }else {
                return R.ok().message("存在未取消审核成功的订单");
            }

        } catch (RuntimeException e) {
            e.printStackTrace();
            return R.error().message("取消审核出错");
        }

    }

    @ApiOperation(value = "移库到移库管理")
    @PostMapping("/addMove")
    public R addMove(@RequestBody Puton moveEntry,HttpServletRequest request){
        String token=request.getHeader("token");
        Long userid= JwtUtils.getMemberIdByJwtToken(token);
        User user=stockService.selectUser(userid);
        String name = user.getName();
        String locatorcode = moveEntry.getLocatorcode();
        String oldLocatorcode = moveEntry.getOldlocatorcode();
        Long warehouseid = moveEntry.getWarehouseid();
        Integer qty = moveEntry.getQty();
        String commoditybar = moveEntry.getCommoditybar();
        try {
            R r = stockService.updateUqtyQuantity(oldLocatorcode, commoditybar, warehouseid, qty);
            if (!r.getSuccess()){
                return R.error().message("数量不足,移库失败");
            }
            moveEntry.setState("1");
            Move move=new Move();
            BeanUtils.copyProperties(moveEntry,move);
            Locator locator = stockService.selectLocator(locatorcode);
            Locator oldlocator=stockService.selectLocator(oldLocatorcode);
            Commodity commodity = stockService.selectCommodity(commoditybar);
            move.setLocatorid(locator.getId());
            move.setLocatorname(locator.getName());
            move.setOldlocatorid(oldlocator.getId());
            move.setOldlocatorname(oldlocator.getName());
            move.setCommodityid(commodity.getId());
            move.setCommodityname(commodity.getName());
            move.setCreateid(userid);
            move.setCreator(name);
            move.setUpdateid(userid);
            move.setUpdator(name);
            moveService.save(move);
            return R.ok().message("移库成功");
        }catch (RuntimeException e){
            e.printStackTrace();
            return R.error().message("移库失败");
        }


    }

    @ApiOperation(value = "移货位中普通库位的下拉")
    @PostMapping("/selectByWarehouseid")
    public R selectByWarehouseid(@RequestBody Map map){
        try{
        String oldLocatorcode =(String)map.get("oldLocatorcode");
        String locatorcode=(String) map.get("locatorcode");
        Long warehouseid = (Long)map.get("warehouseid");
        QueryWrapper<Puton> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("warehouseid",warehouseid);
        if (StringUtils.isNotEmpty(oldLocatorcode)){
            queryWrapper.eq("locatorcode",oldLocatorcode);
        }
        List<Puton> list = putonService.list(queryWrapper);
        return R.ok().message("下拉准备成功").data("puton",list);
    }catch (RuntimeException e){
            e.printStackTrace();
            return R.error().message("下拉查询失败");
        }
    }
    @ApiOperation("移库的下拉")
    @PostMapping("/selectMove")
    public R selectCom(@RequestBody Move move){
        Long warehouseid = move.getWarehouseid();
        String oldlocatorcode = move.getOldlocatorcode();
        Set oldlocatorsSet=new HashSet();
        List<Stock> locators = stockService.selectStockInfo(warehouseid, "1");
        System.out.println(locators);
        for (int i = 0; i <locators.size(); i++){
            oldlocatorsSet.add(locators.get(i).getLocatorcode());
        }
        R r = stockService.selectCommoditybar(oldlocatorcode, warehouseid);
        List<Stock> commoditybars = (List<Stock>)r.getData().get("commoditybars");

        return R.ok().data("commoditybars",commoditybars).data("oldlocatorcodes",oldlocatorsSet);

    }


}

